package com.cmcc.linlaker.ui.upload;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.ProjectListActivity;
import com.cmcc.linlaker.ui.upload.bean.UploadQuestionBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.zyyoona7.picker.DatePickerView;
import com.zyyoona7.picker.base.BaseDatePickerView;
import com.zyyoona7.picker.ex.DayWheelView;
import com.zyyoona7.picker.ex.MonthWheelView;
import com.zyyoona7.picker.ex.YearWheelView;
import com.zyyoona7.picker.listener.OnDateSelectedListener;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class NewCheckingTaskActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_checking_task);

        BarUtils.initStatusBar(this);

        initView();
    }

    private TextView text_taskType, text_endTime, text_problem_name;
    private EditText edit_title, edit_description;

    public void initView() {
        text_taskType = findViewById(R.id.text_taskType);
        text_endTime = findViewById(R.id.text_endTime);
        edit_title = findViewById(R.id.edit_title);
        text_problem_name = findViewById(R.id.text_problem_name);
        edit_description = findViewById(R.id.edit_description);
    }

    public void back(View view) {
        finish();
    }


    private UploadQuestionBean.UploadQuestionData problemData;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000) {
            problemData = (UploadQuestionBean.UploadQuestionData) data.getSerializableExtra("bean");
            if (problemData != null) {
                text_problem_name.setText(problemData.title);
            }
        }
    }

    /**
     * 选择关联问题
     */
    public void selectConnectedProblem(View view) {
        Intent intent = new Intent(NewCheckingTaskActivity.this, ProjectListActivity.class);
        startActivityForResult(intent, 1000);
    }

    /**
     * 选择截止时间
     */
    public void selectEndTime(View view) {
        showDatePicker(findViewById(R.id.layout_new_task));
    }

    private PopupWindow datePopupWindow;

    private void showDatePicker(View view) {
        if (datePopupWindow != null && datePopupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_date_picker, null);
        datePopupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        datePopupWindow.setFocusable(true);
        datePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        datePopupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        datePopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setDatePickerButtonListeners(layout);
        datePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }

    private String selectDate;

    private void setDatePickerButtonListeners(RelativeLayout layout) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final DatePickerView datePickerView = layout.findViewById(R.id.datePickerView);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePopupWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePopupWindow.dismiss();

                text_endTime.setText(selectDate);
            }
        });

        datePickerView.setOnDateSelectedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(BaseDatePickerView datePickerView, int year, int month, int day, @Nullable Date date) {
                //拍摄日期
                selectDate = year + "-" + parseNumber(month) + "-" + parseNumber(day);
            }
        });

        //尽请使用各种方法
        datePickerView.setNormalItemTextColor(0xff666666);
        datePickerView.setSelectedItemTextColor(0xff000000);
        datePickerView.setDividerHeight(12f);
        datePickerView.setTextSize(20, true);
        datePickerView.setShowLabel(false);
        YearWheelView yearWv3 = datePickerView.getYearWv();
        MonthWheelView monthWv3 = datePickerView.getMonthWv();
        DayWheelView dayWv3 = datePickerView.getDayWv();
        yearWv3.setIntegerNeedFormat("%d年");
        monthWv3.setIntegerNeedFormat("%02d月");
        dayWv3.setIntegerNeedFormat("%02d日");

        selectDate = yearWv3.getSelectedYear() + "-" + parseNumber(monthWv3.getSelectedMonth()) + "-" + parseNumber(dayWv3.getSelectedDay());

        yearWv3.setTextBoundaryMargin(16, true);
        monthWv3.setTextBoundaryMargin(16, true);
        dayWv3.setTextBoundaryMargin(16, true);
        datePickerView.setDrawSelectedRect(true);
        datePickerView.setSelectedRectColor(Color.parseColor("#F5F5F5"));
    }

    /**
     * 数字小于10 前面加0
     */
    private String parseNumber(int number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return number + "";
        }
    }

    /**
     * 新建任务
     */
    public void addTask(View view) {
        add();
    }

    /**
     * 新建任务
     */
    private void add() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("name", edit_title.getText().toString());
        params.put("description", edit_description.getText().toString());
        params.put("finishTime", text_endTime.getText().toString());
        params.put("userid", SPHelper.getUid());
        params.put("type", "");
        if (problemData != null) {
            params.put("problemid", problemData.id);
        }

        helper.sendPOSTRequest(ApiDefine.TASK_ADD, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
                        ToastUtils.showText(NewCheckingTaskActivity.this, "任务新建成功");
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(NewCheckingTaskActivity.this);
                    } else {
                        ToastUtils.showText(NewCheckingTaskActivity.this, bean.msg);
                    }
                }
            }
        });
    }

}
